<?php

namespace App\SmsCommon\Sms;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Overtrue\EasySms\EasySms;

class SmsCommon
{
    public static function getSms()
    {
        $alisms_config = config('sms');

        if (empty($alisms_config)) {
            throw  new \Exception('阿里短信配置不为空');
        }

        $config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,

            //单个手机每日发送上限
            'maxPhoneCount' => 10,
            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
                // 默认可用的发送网关
                'gateways' => [
                    'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => '/tmp/easy-sms.log',
                ],
                'aliyun' => [
                    'access_key_id' => $alisms_config['access_key'],
                    'access_key_secret' => $alisms_config['secret_key'],
                    'sign_name' => $alisms_config['sign'],
                    'template_code' => $alisms_config['template_code'],
                ],
            ],
        ];

        return new EasySms($config);
    }

    /**
     * 发送注册验证码
     *
     * @param $phone
     * @return array
     */
    public static function sendRegisterSms($phone)
    {
        //判断
        if (empty($phone)) {
            return ['mark' => false, 'message' => '手机号不能为空'];
        }

        //key
        $smsKey_time = 'register:verification_time_' . $phone;

        //读取缓存
        if (Cache::get($smsKey_time)) {

            return ['mark' => false, 'message' => '一分钟内只能发送一次!'];
        }

        // 模板
        $template_code = config('sms.front.register_sms_template');

        //随机验证码
        $code = mt_rand(1000, 9999);

        //调用发送验证码的方法  compact:建立一个数组，包括变量名和它们的值
        $result = self::sendCode($phone, $template_code, compact('code'));

        //判断验证码正确
        if ($result == true) {
            // 缓存的key 缓存验证码
            $smsKey = 'register:verification_' . $phone;
            Cache::put($smsKey, $code, Carbon::now()->addMinutes(10));
            //一分钟的时效
            Cache::put($smsKey_time, time(), Carbon::now()->addMinutes(1));
            return ['mark' => true, 'message' => '发送成功!'];
        } else {
            return ['mark' => false, 'message' => '发送失败!'];
        }
    }


    /**
     * @param $phone
     * @param $code
     * @return bool
     */
    public static function checkRegisterCode($phone, $code)
    {
        //key
        $smsKey = 'register:verification_' . $phone;

        if (Cache::get($smsKey) == $code) {
            return true;
        }

        return false;
    }

    /**
     * 发送忘记密码验证码
     *
     * @param $phone
     * @return array
     */
    public static function sendForgetSms($phone)
    {
        if (empty($phone)) {
            return ['mark' => false, 'message' => '手机号不能为空'];
        }

        $smsKey_time = 'forget:verification_time_' . $phone;

        if (Cache::get($smsKey_time)) {
            return ['mark' => false, 'message' => '一分钟内只能发送一次!'];
        }

        // 模板
        $template_code = config('sms.front.forget_sms_template');

        $code = mt_rand(1000, 9999);

        $result = self::sendCode($phone, $template_code, compact('code'));

        if ($result == true) {
            // 缓存的key
            $smsKey = 'forget:verification_' . $phone;
            Cache::put($smsKey, $code, Carbon::now()->addMinutes(10));
            Cache::put($smsKey_time, time(), Carbon::now()->addMinutes(1));
            return ['mark' => true, 'message' => '发送成功!'];
        } else {
            return ['mark' => false, 'message' => '发送失败!'];
        }
    }

    /**
     * @param $phone
     * @param $code
     * @return bool
     */
    public static function checkForgetCode($phone, $code)
    {
        $smsKey = 'forget:verification_' . $phone;

        if (Cache::get($smsKey) == $code) {
            return true;
        }

        return false;
    }


    /**
     * 发送验证码
     *
     * @param $phone
     * @param $template_code
     * @param $data
     * @return bool
     */
    public static function sendCode($phone, $template_code, $data)
    {
        try {
            info($data);
            $result = self::getSms()->send($phone, [
                'template' => $template_code,
                'data' => $data,
            ]);

            if ($result['aliyun']['status'] == 'success') {
                return true;
            }

            return false;
        } catch (\Exception $e) {
            info($e);
            $e->getExceptions();
        }
    }


    /**
     * 发送注册验证码
     *
     * @param $phone
     * @return array
     */
    public static function sendVerifySms($phone)
    {
        if (empty($phone)) {
            return ['mark' => false, 'message' => '手机号不能为空'];
        }

        $smsKey_time = 'verify:verification_time_' . $phone;

        if (Cache::get($smsKey_time)) {
            return ['mark' => false, 'message' => '一分钟内只能发送一次!'];
        }

        // 模板
        $template_code = config('sms.front.verify_sms_template');

        $code = mt_rand(1000, 9999);

        $result = self::sendCode($phone, $template_code, compact('code'));

        if ($result == true) {
            // 缓存的key
            $smsKey = 'verify:verification_' . $phone;
            Cache::put($smsKey, $code, Carbon::now()->addMinutes(10));
            Cache::put($smsKey_time, time(), Carbon::now()->addMinutes(1));
            return ['mark' => true, 'message' => '发送成功!'];
        } else {
            return ['mark' => false, 'message' => '发送失败!'];
        }
    }


    /**
     * @param $phone
     * @param $code
     * @return bool
     */
    //注册验证码
    public static function checkVerifyCode($phone, $code)
    {
        $smsKey = 'verify:verification_' . $phone;

        if (Cache::get($smsKey) == $code) {
            return true;
        }

        return false;
    }
}
